import { _decorator, Component, Node, BoxCollider, ICollisionEvent, director } from 'cc';
import { PlayerMovement } from './PlayerMovement';
const { ccclass, property } = _decorator;


@ccclass('PlayerCollision')
export class PlayerCollision extends Component {

    start() {
        // 打开碰撞监听
        let collider = this.node.getComponent(BoxCollider);  // 所有的Box碰撞体
        collider.on('onCollisionEnter', this.onCollisionEnter, this);

        // 打开终点触发器监听
        collider.on('onTriggerEnter', this.onTriggerEnter, this);
    }

    onDestroy() {
        // 关闭碰撞监听
        let collider = this.node.getComponent(BoxCollider);
        collider.off('onCollisionEnter', this.onCollisionEnter, this);

        // 关闭终点触发器监听
        collider.off('onTriggerEnter', this.onTriggerEnter, this);
    }

    onCollisionEnter(event: ICollisionEvent) {
        // 实现碰撞逻辑，碰到障碍物
        console.log('hit, you lose');
        if(event.otherCollider.node.name == 'Obstacle') {  // 只有在被碰撞的目标是障碍物的时候才需要屏蔽PlayerMovement
            // 屏蔽PlayerMovement
            let movement = this.node.getComponent(PlayerMovement);
            movement.enabled = false;

            // 抛出一个level_failed事件
            director.getScene().emit('level_failed');
        }
    }

    onTriggerEnter(event: ICollisionEvent) {
        // 到达终点
        console.log('you win!!!');
        if(event.otherCollider.node.name == 'End') {
            console.log("WIN!!!!!!!!!!!!");
            let movement = this.node.getComponent(PlayerMovement);
            movement.enabled = false;

            // 完成当前关卡
            if(director.getScene().name == 'level-003') {
                director.getScene().emit('level_completed');  // 抛出一个level_completed事件
            } else {
                director.getScene().emit('level_succeed');  // 抛出一个level_succeed事件
            }
        }
    }

    update(deltaTime: number) {
        
    }

}